const router = require('express').Router()
const md5 = require('md5')
const salt = "AKJDLKAsjdoiqwjdl;aSldaa,dlqlwekl,sadASDdadqthis.q"
const jsonwebtiken = require('jsonwebtoken')
const db = require('../db')
// 使用fs,path写入图片
const fs = require('fs')
const path = require('path')
// 使用multer解析图片buffer
const multer = require('multer')
// 保存地址
const catalog = '../public/image/'
// 访问基地址
const fileBaseUrl = 'http://127.0.0.1:9999/api/v1/public/image/'

// 登录接口
router.post('/login', (req, res) => {

    let mobile = req.body.mobile
    let password = req.body.password
    // 验证数据
    let mobileRe = /^1(3|5|7|8|9)\d{9}$/
    if (mobileRe.test(mobile) || mobile.length < 20) {

    } else {
        res.json({
            'ok': 0,
            'error': '手机号码或用户名不正确!'
        })
        return
    }


    let passwordRe = /^[0-9a-zA-Z_]{6,18}$/
    if (!passwordRe.test(password)) {
        res.json({
            'ok': 0,
            'error': '密码必须是6~18位数字，下划线，字母'
        })
        return
    }
    // SELECT id,password FROM shop_users WHERE mobile= '肖乐融' or username='肖乐融';
    // 根据手机号码到用户表查询是否有这个账号
    let sql = `SELECT id,password FROM shop_users WHERE mobile= '${mobile}' or username='${mobile}'`
    db.query(sql, (err, data) => {
        if (err) {
            res.json({
                'ok': 0,
                'error': "手机号码或用户名不存在!"
            })
            return
        } else {
            if (data.length > 0) {
                if (data[0].password === md5(password + salt)) {
                    let jwt = jsonwebtiken.sign({
                        id: data[0].id
                    }, salt, {
                        expiresIn: 60 * 60 * 24 * 30 * 6
                    })
                    res.json({
                        'ok': 1,
                        'data': {
                            'token': jwt,
                            'id': data[0].id
                        }
                    })
                } else {
                    res.json({
                        'ok': 0,
                        'error': '密码错误!'
                    })
                    return
                }
            } else {
                res.json({
                    'ok': 0,
                    'error': '手机号或用户名不存在!'
                })
                return
            }
        }
    })


})

// 获取时间戳
router.get('/regtime', (req, res) => {
    let mobile = req.query.mobile
    let sql = `SELECT regtime from shop_users WHERE mobile ='${mobile}' or username = '${mobile}'`
    db.query(sql, (err, result) => {
        if (err) {
            console.log(err)
        } else {
            res.json({
                'ok': 1,
                'data': result
            })
        }
    })
})

// 获取昵称
router.get('/username', (req, res) => {
    let mobile = req.query.mobile
    let sql = `SELECT username from shop_users WHERE mobile ='${mobile}' or username = '${mobile}'`
    db.query(sql, (err, result) => {
        if (err) {
            console.log(err)
        } else {
            res.json({
                'ok': 1,
                'data': result
            })
        }
    })
})


// 修改昵称
router.get('/upUsername', (req, res) => {
    let mobile = req.query.mobile
    let username = req.query.username
    db.query(`UPDATE shop_users SET username = '${username}' WHERE username = '${mobile}' or mobile = '${mobile}'`, (err, result) => {
        if (err) {
            console.log(err)
        } else {
            res.json({
                'ok': 1,
                'message': "保存成功!"
            })
        }
    })
})

// 修改密码
router.get('/upPassword', (req, res) => {
    let mobile = req.query.mobile
    let password = md5(req.query.password + salt)
    db.query(`UPDATE shop_users SET password = '${password}' WHERE username = '${mobile}' or mobile = '${mobile}'`, (err, result) => {
        if (err) {
            console.log(err)
        } else {
            res.json({
                'ok': 1,
                'message': "修改成功!"
            })
        }
    })
})

// 获取头像
router.get('/image', (req, res) => {
    let mobile = req.query.mobile
    let sql = `SELECT image from shop_users WHERE mobile ='${mobile}' or username = '${mobile}'`
    db.query(sql, (err, result) => {
        if (err) {
            console.log(err)
        } else {
            res.json({
                'ok': 1,
                'data': result
            })
        }
    })
})

// 修改头像
router.post('/upImage',multer().single('img'), (req, res) => {
    // console.log(req.body);
    
    let mobile = req.body.mobile
    // let img = req.body.formdata.img
    let {
        buffer,
        originalname
      } = req.file
    
      fs.writeFileSync(path.join(__dirname, catalog + originalname), buffer)
    
    // console.log(req.body);
    // let originalname = '22.txt'
    // fs.writeFileSync(path.join(__dirname, catalog + originalname), mobile)
    // res.json({
    //     ok: 1,
    //     url: fileBaseUrl + originalname
    // })
        db.query(`UPDATE shop_users SET image = '${fileBaseUrl + originalname}' WHERE username = '${mobile}' or mobile = '${mobile}'`,(err,result)=>{
    if(err){
        console.log(err)
    }else{
        res.json({
            'ok':1,
            'img':fileBaseUrl + originalname
        })
    }
        })
})
router.get('/public/image/*', (req, res) => {
    let imgName = req.params[0]
    // console.log(imgName);
    res.sendFile(path.join(__dirname, catalog + imgName))
})
// 获取性别
router.get('/gender', (req, res) => {
    let mobile = req.query.mobile
    let sql = `SELECT gender from shop_users WHERE mobile ='${mobile}' or username = '${mobile}'`
    db.query(sql, (err, result) => {
        if (err) {
            console.log(err)
        } else {
            res.json({
                'ok': 1,
                'data': result
            })
        }
    })

    // 修改性别
    router.post('/upGender', (req, res) => {
        let mobile = req.body.mobile
        let gender = req.body.gender
        db.query(`UPDATE shop_users SET gender = '${gender}' WHERE username = '${mobile}' or mobile = '${mobile}'`, (err, result) => {
            if (err) {
                console.log(err)
            } else {
                res.json({
                    'ok': 1,
                    'message': "修改成功!"
                })
            }
        })
    })

    // 获取支付密码
    router.get('/payPassword', (req, res) => {
        let mobile = req.query.mobile
        let sql = `SELECT pay_password from shop_users WHERE mobile ='${mobile}' or username = '${mobile}'`
        db.query(sql, (err, result) => {
            if (err) {
                console.log(err)
            } else {
                res.json({
                    'ok': 1,
                    'data': result
                })
            }
        })
    })


    // 修改支付密码
    router.get('/upPay_password', (req, res) => {
        let mobile = req.query.mobile
        let pay_password = req.query.pay_password
        db.query(`UPDATE shop_users SET pay_password = '${pay_password}' WHERE username = '${mobile}' or mobile = '${mobile}'`, (err, result) => {
            if (err) {
                console.log(err)
            } else {
                res.json({
                    'ok': 1,
                    'message': "修改成功!"
                })
            }
        })
    })

})

module.exports = router